﻿using HuaweiCloud.Dotnet.Samples.Common;
using HuaweiCloud.Dotnet.Samples.Common.Cache.Extension;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Dtos;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Entities;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Specification;
using Microsoft.Extensions.Caching.Distributed;

namespace HuaweiCloud.Dotnet.Samples.ESports.Main.Service
{
    public class UserService : IUserService
    {
        private readonly IRepository<User> _repository;
        private readonly IDistributedCache _cache;
        private readonly string _key = RedisConst.User;
        public UserService(IRepository<User> repository
            , IDistributedCache cache)
        {
            _repository = repository;
            _cache = cache;
        }
        public async Task<UserLoadedDto> GetUsersByIdsAsync(IEnumerable<Guid> ids, CancellationToken token = default)
        {
            var info = await _cache.GetAsync<UserLoadedDto>(_key, token);
            info ??= new UserLoadedDto();
            var map = info.Data;
            var rqs = new List<Guid>();
            foreach (var id in ids)
                if (!map.ContainsKey(id))
                    rqs.Add(id);
            if(rqs.Count > 0)
            {
                var users = await _repository.ListAsync(new UserSpecification(rqs));
                foreach (var user in users)
                {
                    map.TryAdd(user.Id, user.NickName);
                }
                var expired = DateTime.Today;
                // 用户信息过期时间为次日凌晨0点
                expired = expired.AddDays(1);
                var option = new DistributedCacheEntryOptions()
                {
                    AbsoluteExpiration = new DateTimeOffset(expired)
                };
                await _cache.SetAsync(_key, info, option, token);
            }
            return info;
        }
    }
}
